const express = require("express");
const router = express.Router();
const userCtrl = require("../controllers/user");

router.get("/:id", (req, res) => {
  const u = userCtrl.getUserById(req.params.id);
  if (!u) {
    res.redirect('error', { error: new Error("User not found") });
  }
  res.render('user', {
    title: "User",
    user: u,
  });
});
router.put("/", (req, res) => {  
  userCtrl.update(req.body.id, req.body.name);
  res.redirect("users/" + req.body.id);
});
router.get("/", (req, res) => {
  res.render('users', {
    title: "Users",
    users: userCtrl.getAllUsers(),
  });
});
router.delete('/', (req, res) => {
  try {
    userCtrl.delete(req.body.id);
    res.redirect('/users');
  } catch (error) {
    res.render('error', { error });
  }
});
router.post('/', (req, res) => {
  userCtrl.add(req.body.name);
  res.redirect('/users');
});



exports = module.exports = router;